package com.hdl.school.utils;


import com.leectrl.utils.HexUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SignUtil {
    public static String genDynamicQrParams(int schoolId, int roomId) {
        int time = (int) (System.currentTimeMillis() / 1000);
        String paramsStr = "";
        String timeStr = String.valueOf(time);

        timeStr =timeStr.substring(7, 10)+timeStr.substring(4, 7) +timeStr.substring(0, 4);
        System.out.println("ccc:"+String.valueOf(time)+"/"+timeStr);
        char[] charArr = timeStr.toCharArray();
        int pad = 33;
        if (roomId >= 100) {
            String roomStr = String.valueOf(roomId);
            pad = Integer.parseInt(roomStr.substring(roomStr.length() - 2));
        } else {
            pad = roomId;
        }
        for (char c : charArr) {
            String s = Integer.toHexString((int) c + pad);
            if (s.length() < 0) {
                s = "0" + s;
            }
            paramsStr += s.toUpperCase();
        }
        String schoolHex = Integer.toHexString(schoolId);
        while (schoolHex.length()<6){
            schoolHex="0"+schoolHex;
        }
        String roomHex = Integer.toHexString(roomId);
        while (roomHex.length()<6){
            roomHex="0"+roomHex;
        }
        return schoolHex.toUpperCase()+roomHex.toUpperCase()+paramsStr;
    }

    public static boolean checkDynamicPassword(int roomId,String password) {
        long now=System.currentTimeMillis();
        if(now>1672502400000L){
            long durTime=now-now%300000;
            int room=roomId%100;
            String numStr=String.valueOf((durTime/10000)*room*57);
            return numStr.substring(numStr.length()-9,numStr.length()-3).equals(password);
        }else{
            String n=String.valueOf(roomId*964782);
            return n.substring(n.length()-6).equals(password);
        }
    }

    public static String md5(String text) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(text.getBytes());
            result = HexUtil.bytes2HexString(digest);
        } catch (NoSuchAlgorithmException ex) {
            ex.printStackTrace();
        }
        return result;
    }

}
